package kr.hyosang.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;


public class NetManager {
	public static enum RequestType {GET, POST};
	
	public static String getWebContent(String url) {
		return getWebContent(url, RequestType.GET, Charset.forName("UTF-8"), null, null);
	}
	
	public static String getWebContent(String url, RequestType reqType, Charset resCharset, String postBody, Charset reqCharset) {
		try {
			URL objUrl = new URL(url);
			
			URLConnection conn = objUrl.openConnection();
			conn.setDoInput(true);
			if(reqType == RequestType.POST) {
				conn.setDoOutput(true);
			}
			
			conn.connect();
			
			if(reqType == RequestType.POST) {
				OutputStream os = conn.getOutputStream();
				os.write(postBody.getBytes(reqCharset));
				os.flush();
			}
			
			InputStream is = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, resCharset));
			
			StringBuffer sb = new StringBuffer();
			String line;
			
			while( (line = br.readLine()) != null) {
				sb.append(line);
				sb.append("\n");
			}
			
			br.close();
			is.close();
			
			return sb.toString();
		}catch(MalformedURLException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		
		return null;
	}

}
